<?php
/**
* Copyright (c) 2002-2007 BioWare Corp.
* http://www.bigdaddymonitor.org
*
* This file is part of the BigDaddy Monitoring
* program. It is free software distributed under
* the terms of the BSD License. It is ditributed
* in the hopes that it will be useful, but
* WITHOUT ANY WARRANTY; without event the implied
* warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE.
*
* The BSD License is available from:
* http://www.opensource.org/licenses/bsd-license.php
**/
/*===========================================================================================*/
//BigDaddy DB Functions
//This provides and creates the connections to the correct databases
//Remember BIGDADDY should NEVER connect to Any DB BUT BIGDADDY 
//DW 03.12.04
/*===========================================================================================*/

//Include the DB Read Class
require("class_dbread.inc");


/*===========================================================================================*/
//Function gets a result array from a database query. Runs all select queries on Read Servers
//run_mysql_query(string SQLstr)
//DW
/*===========================================================================================*/
function run_mysql_query($sql, $special=NULL)
{
    global $dbh;
    
    $result=mysql_query($sql, $dbh);
            
    if ($special=="getInsertID")
    {
       return mysql_insert_id($dbh);
    }
            
    return $result;
}

/*===========================================================================================*/
//Function To count the queries that are happening
//query_count($sType[, $%bReturn])
//DW
/*===========================================================================================*/
function query_count($sType, $bReturn=NULL)
{
	static $nSelect = 0;
	static $nInsert = 0;
	static $nUpdate = 0;
	static $nOther = 0;

	switch ($sType)
	{
		case "select":
			if ($bReturn==1)
			{
				return $nSelect;
			}
			$nSelect++;
			break;
		case "insert":
			if ($bReturn==1)
			{
				return $nInsert;
			}
			$nInsert++;

			break;
		case "update":
			if ($bReturn==1)
			{
				return $nUpdate;
			}
			$nUpdate++;
			break;
		case "other":
		default:
			if ($bReturn==1)
			{
				return $nOther;
			}
			$nOther++;
			break;
	}
}


/*===========================================================================================*/
//Function gets a result array from a database query. Runs all select queries on Read Servers
//run_mysql_query(string SQLstr)
//DW
/*===========================================================================================*/
function db_query($sSql, $aOptions=NULL)
{
    global $dbh, $newDBRead;

	//Keeps a count of various types of queries
    if (preg_match("/^([a-zA-Z]+)/", $sSql, $aMatches))
    {
		if (SQLDEBUG==1 && strtolower($aMatches[1])!="explain")
		{
			query_count(strtolower($aMatches[1]));
			query_log($sSql);
		}
    }
	
	if ($aOptions["dbHandle"]!="")
	{
		$dbhQuery=$newDBRead->GetSpecificHandle($aOptions["dbHandle"]);
	}
	else
	{
		$dbhQuery=$dbh;
	}
	
	$resResult=mysql_query($sSql, $dbhQuery);
	
	if (($aOptions["getInsertID"]==true || $aOptions["getInsertID"]==1) && $resResult==true)
	{
		return mysql_insert_id($dbhQuery);
	}
	
	if (($aOptions["getAffectedRows"]==true || $aOptions["getAffectedRows"]==1) && $resResult==true)
	{
		return mysql_affected_rows($dbhQuery);
	}
	
	return $resResult;
}

/*===========================================================================================*/
//Function To Log Queries
//query_log(mixed LogData)
//DW
/*===========================================================================================*/
function query_log($mLogData)
{
	static $bFileSelect = 0;
	$sString="";

	//If we have not ever gone through this function then we want
    //to get rid of any old files
	if ($bFileSelect==0)
	{
		$bFileSelect=1;
		$sString.="\n===============================================================================\n";
		$sString.="FILENAME: ".$_SERVER["SCRIPT_NAME"]." / ".get_time_str(time(),3);
		$sString.="\nQUERYSTRING: ".$_SERVER["QUERY_STRING"];
		$sString.="\n===============================================================================\n";
	}
	
	if (is_string($mLogData))
	{
		$sString.="STATEMENT: ".$mLogData;
		
		//If it's a select statement we want to run an explain. Note that this will only work with
        //the main database as this function doesn't yet know about switching dbs etc.
		
		if (preg_match("/^([a-zA-Z]+)/", $mLogData, $aMatches))
		{
			if (strtolower($aMatches[1])=="select")
			{
				$sql = "explain ".$mLogData;
				$sString.= "\n\nEXPLAIN STATEMENT: ".$sql."\n";
				
				//Sends in the PREVENTSQLDEBUG FLAG so this function isn't called again.
				$aResult = db_fetch_array(db_query($sql), 1);
				
				for ($i=0; $i<count($aResult); $i++)
				{
					$sString.="\nID: ".$aResult[$i]["id"]." / SELECT TYPE: ".$aResult[$i]["select_type"]." / TABLE: ".$aResult[$i]["table"]." / TYPE: ".$aResult[$i]["type"]." / POSSIBLE KEYS: ".$aResult[$i]["possible_keys"]." / KEY: ".$aResult[$i]["key"]." / KEY LENGTH: ".$aResult[$i]["key_len"]." / REF: ".$aResult[$i]["ref"]." / ROWS: ".$aResult[$i]["rows"]." / EXTRA: ".$aResult[$i]["Extra"];
				}
			}
		}
	}
	
	if (is_array($mLogData))
	{
		$sString.="RESULTSET: \n".print_r($mLogData, true);
	}
	
	$sString.="\n\n Select: ".query_count("select", 1)." / Insert: ".query_count("insert", 1)." / Update: ".query_count("update", 1)." / Other: ".query_count("other", 1);
	$sString.="\n-------------------------------------------------------------------\n";
	
	//OPen file handle
    $fh=fopen(LOG_SQLDEBUG, "a");
	fwrite($fh, $sString);
	fclose($fh);
	
}

/*===========================================================================================*/
//Function takes database result and converts it to a regular php array
//Added optional flag PREVENTSQLDEBUG as a force into db_fetch_array
//db_fetch_array(resource $result, bool PREVENTSQLDEBUG)
//DW
/*===========================================================================================*/
function db_fetch_array($result, $PREVENTSQLDEBUG=NULL)
{
    if (@mysql_num_rows($result)>0)
    {
		$i=0;
		while ($row=mysql_fetch_array($result))
		{
			foreach ($row as $key => $value)
			{
				$returnArray[$i][$key]=$value;
			}
			$i++;
		}
		if (SQLDEBUG==1 && $PREVENTSQLDEBUG!=1)
		{
			query_log($returnArray);
		}
		return $returnArray;
    }
	else
    {
		return 0;
    }
}

/*===========================================================================================*/
//Function takes database result and converts the row into to a regular php array
//Added optional flag PREVENTSQLDEBUG as a force into db_fetch_result
//db_fetch_result(resource $result, bool PREVENTSQLDEBUG)
//DW
/*===========================================================================================*/
function db_fetch_result($result, $PREVENTSQLDEBUG=NULL)
{
    if (@mysql_num_rows($result)==1)
    {
		$array=mysql_fetch_array($result);
		foreach ($array as $key => $value)
		{
			$returnArray[$key]=$value;
		}
		if (SQLDEBUG==1 && $PREVENTSQLDEBUG!=1)
		{
			query_log($returnArray);
		}
		return $returnArray;
    }
    else
    {
		return 0;
    }
}

/*===========================================================================================*/
//Function takes database result returns just the number of rows in the result.
//db_num_rows(resource $result)
//DW
/*===========================================================================================*/
function db_num_rows($result)
{
    if ($result)
    {
		return @mysql_num_rows($result);
    }
}

/*===========================================================================================*/
//Function takes string and escapes string for insertion into DB
//db_escape_string(mixed $data)
//DW
/*===========================================================================================*/
function db_escape_string($data)
{
    if ($data!="")
    {
		return @mysql_real_escape_string(stripslashes($data), $GLOBALS["dbh"]);
    }
}


$newDBRead=new DatabaseHandle("bigdaddy");
$dbh=$newDBRead->GetSpecificHandle("bigdaddy");
?>
